package com.xxl.job.executor.utils;

import com.xxl.job.core.context.XxlJobHelper;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class Helper {

    /**
     * 返回当前日期减一的字符串
     *
     * @return 当前日期减一的字符串
     */
    public String getStartDate() {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        return formatter.format(calendar.getTime());
    }

    /**
     * 获取参数
     *
     * @return 参数map
     */
    public static Map<String, Object> getParams() {
        Map<String, Object> result = new HashMap<>();
        String param = XxlJobHelper.getJobParam();
        String startdt = "";
        String enddt = "";
        String type = "";
        if (param != null && !param.isEmpty()) {
            String[] httpParams = param.split("\n");
            for (String httpParam : httpParams) {
                if (httpParam.startsWith("type:")) {
                    type = httpParam.substring(httpParam.indexOf("type:") + 5).trim();
                }
                if (httpParam.startsWith("startdt:")) {
                    startdt = httpParam.substring(httpParam.indexOf("startdt:") + 8).trim();
                }
                if (httpParam.startsWith("enddt:")) {
                    enddt = httpParam.substring(httpParam.indexOf("enddt:") + 6).trim();
                }
            }
        }
        //创建日期时间对象格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //开始时间为空取昨天0点
        LocalDateTime parseStartDate = startdt.equals("") ? LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN)
                : LocalDateTime.parse(startdt + " 00:00:00", formatter);
        LocalDateTime parseEndDate = enddt.equals("") ? LocalDateTime.now() : LocalDateTime.parse(enddt + " 23:59:59", formatter);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        result.put("type", type);
        result.put("startdt", parseStartDate.format(dtf));
        result.put("enddt", parseEndDate.format(dtf));
        return result;
    }

    public static String getMapValue(Map<String, Object> map, String key) {
        if (map.containsKey(key)) {
            return map.get(key) == null ? "" : map.get(key).toString();
        }
        return "";
    }
}
